
package lifecraft;

import java.util.*;

import org.lwjgl.LWJGLException;

import java.io.FileInputStream;
import java.io.IOException;
import org.lwjgl.Sys;

import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.input.Mouse;
import org.lwjgl.input.Keyboard;

import org.newdawn.slick.Color;





public class LifeCraft {
 
    static public final int R_WIDTH = 1024; 
    static public final int R_HEIGHT = 768;
    World world;
    MenuGame g_menu = new MenuGame(this);
    
    private boolean exit;
    Equipment equipment; 
    
    public boolean fullscreen;
    /**
    * Set the display mode to be used 
    * 
    * @param width The width of the display required
    * @param height The height of the display required
    * @param fullscreen True if we want fullscreen mode
    */
    public void setDisplayMode(int width, int height, boolean fullscreen){
        
        //wyjdź jeśli wybrany rodzaj wyświetlania jest taki jak aktualny
        if ((Display.getDisplayMode().getWidth() == width) && 
                (Display.getDisplayMode().getHeight() == height) && 
                (Display.isFullscreen() == fullscreen)){
            return;
        }
        
        try {
            DisplayMode targetDisplayMode = null;
            
            if (fullscreen){
                DisplayMode[] modes = Display.getAvailableDisplayModes();
                int freq = 0;
            
                for(int i=0;i<modes.length; i++){
                    DisplayMode current = modes[i];
                    
                    //sprawdzanie czy wybrana wysokosc i szerokosc ekranu jest obsługiwana przez karte graficzną.
                    //dodatkowo szukamy jak najlepszej freq i liczby bitów w pixelu
                    if ((current.getWidth() == width) && (current.getHeight() == height)){
                        if ((targetDisplayMode == null)||(current.getFrequency() >= freq)){
                            if ((targetDisplayMode == null) || (current.getBitsPerPixel() > targetDisplayMode.getBitsPerPixel())){
                                targetDisplayMode = current;
                                freq = targetDisplayMode.getFrequency();
                            }
                        }
                        //jeżeli freq i liczba bitow na pixel się zgadza z tymi ustawionymi na naszym pulpicie
                        // (co oznacza ze jest to dobry wybór) to od razu wybiera i wychodzi z petli
                        if ((current.getBitsPerPixel() == Display.getDesktopDisplayMode().getBitsPerPixel()) &&
                                (current.getFrequency() == Display.getDesktopDisplayMode().getFrequency())) {
                            targetDisplayMode = current;
                            break;
                        }                    
                    }
                }
            }
            else{
                targetDisplayMode = new DisplayMode(width, height);
            }
            
            if (targetDisplayMode == null){
                System.out.println("Failed to find value mode: "+width+"x"+height+" fs="+fullscreen);;
            }
            else{
                Display.setDisplayMode(targetDisplayMode);
                Display.setFullscreen(fullscreen);
            }
        }
        catch(LWJGLException e) {
            System.out.println("Unable to setup mode "+width+"x"+height+" fullscreen="+fullscreen + e);
        }
    }
    
    public void init(){
      
        try{
            fullscreen = false;
            setDisplayMode(R_WIDTH,R_HEIGHT,fullscreen);  
            Display.setTitle("GRA");
            Display.create();
            //Display.setVSyncEnabled(true); //z tym nie działa display.sync(fps)!!!
        } catch(LWJGLException e) {
            e.printStackTrace();
            System.exit(0);
        }
        
        GL11.glEnable(GL11.GL_TEXTURE_2D);
        GL11.glShadeModel(GL11.GL_SMOOTH);
        GL11.glDisable(GL11.GL_DEPTH_TEST);
        GL11.glDisable(GL11.GL_LIGHTING);
        GL11.glClearColor(0.f, 0f, 1f,0.0f);
        GL11.glClearDepth(1);       
        GL11.glEnable(GL11.GL_ALPHA);
        GL11.glEnable(GL11.GL_BLEND);
        GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);      
        GL11.glViewport(0,0,R_WIDTH,R_HEIGHT);
        
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        GL11.glOrtho(0, R_WIDTH, R_HEIGHT, 0, 1, -1);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);

        FontBase.get().init();
        SurfaceBase.get().init();
        world = new World();
        g_menu = new MenuGame(this);
        equipment = new Equipment();
    }
    
    public void run()
    {
        Time.get().initTime();
        while((!Display.isCloseRequested())&&(!exit)) {
      
            GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);

            GL11.glMatrixMode(GL11.GL_PROJECTION);
            GL11.glLoadIdentity();
            GL11.glOrtho(world.x, R_WIDTH+world.x, world.y ,R_HEIGHT+world.y, 1, -1);
            GL11.glMatrixMode(GL11.GL_MODELVIEW);
            world.Draw(Time.pause);



            GL11.glMatrixMode(GL11.GL_PROJECTION);
            GL11.glLoadIdentity();
            GL11.glOrtho(0, R_WIDTH, R_HEIGHT, 0, 1, -1);
            GL11.glMatrixMode(GL11.GL_MODELVIEW);

            equipment.renderQuick();


               
            

            FontBase.get().f0.write(900,10,""+Time.get().getGameTime("sek"), Color.yellow);
            FontBase.get().f0.write(900,30,""+Time.get().fpsNumber, Color.yellow);
            if(!g_menu.menu){  
                input();
            }
            else{
                g_menu.menuGame();
                exit = g_menu.exit;
            }
            Display.update();    
            Display.sync(60); 
            Time.get().updateFpsCounter();
            
        }
    
    }

    public void input(){
        
        
        if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
	    world.x-=2;
        }
        if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
            world.x+=2;
        }
        if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
	    world.y+=2;
        }
        if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
	    world.y-=2;
        }
        if ((equipment.quick[equipment.quick_choice].ID == SurfC.WATER)&&(Mouse.isButtonDown(1))){
            int x = Mouse.getX();
            int y = Mouse.getY();
            world.insertAt(x,y,SurfC.WATER);
        }
        
        
        while(Mouse.next()|| Keyboard.next()){
            if (Mouse.getEventButtonState()) {
                if (Mouse.getEventButton() == 0){                                   
                    int x = Mouse.getX();
                    int y = Mouse.getY();     
                    world.destroyAt(x,y);
                    }
                
                if (Mouse.getEventButton() == 1) {
                    int x = Mouse.getX();
                    int y = Mouse.getY();
                    world.insertAt(x,y,equipment.quick[equipment.quick_choice].ID);
		}
                /*if (Mouse.getEventButton() == 2) {
                    world.insertAt(x,y,1);
		}*/
            }
            if (Keyboard.getEventKeyState()) {
	        switch(Keyboard.getEventKey()){
                
                    case Keyboard.KEY_F:
                        System.out.println("F");
                        fullscreen = (fullscreen?false:true);
                        setDisplayMode(1024,768,fullscreen);   
                        break;
                    case Keyboard.KEY_R:
                        world.reset();
                        break;
                    case Keyboard.KEY_ESCAPE:
                        Keyboard.destroy();
                        Mouse.destroy();
                        try{
                            Keyboard.create();
                            Mouse.create();
                        }
                        catch(LWJGLException e) {
                            System.out.println("Unable to create Mouse or Keyboard"+ e);
                        }
                        
                        Time.get().pauseGame();
                        g_menu.menu=true;
                        g_menu.first_animation = true;
                        g_menu.y_anim = R_HEIGHT/2;
                        Time.get().put(g_menu.ch_index);
                        g_menu.choice = 0;
                        System.out.println("PAUSE");
                        break;
                    case Keyboard.KEY_E:
                        //equipment=(equipment?false:true);
                        break;
                    case Keyboard.KEY_1:
                    case Keyboard.KEY_2:
                    case Keyboard.KEY_3:
                    case Keyboard.KEY_4:
                    case Keyboard.KEY_5:
                    case Keyboard.KEY_6:
                    case Keyboard.KEY_7:
                    case Keyboard.KEY_8:
                    case Keyboard.KEY_9:
                        equipment.quick_choice = Keyboard.getEventKey()-2;
                        
                        break;
                    case Keyboard.KEY_0:
                        equipment.quick_choice = 9;     
                        break;
                
                
                }
            }
        }

    
    
    }
    
    public static boolean mouseBlock(int x, int y, int w, int h){
        if((Mouse.getX()<=R_WIDTH - x)&&(Mouse.getX()>=R_WIDTH - (x+w))){
           if((Mouse.getY()<=R_HEIGHT - y)&&(Mouse.getY()>=R_HEIGHT - (y+h)))
              return true;
        }
        return false;
    } 
    
    
    public static void main(String[] args) {
        LifeCraft lifecraft = new LifeCraft();
        lifecraft.init();
        lifecraft.run();
    }
}
